package com.sgu6.middleware.log;

import android.os.Environment;
import android.util.Log;

import com.sgu6.middleware.manager.ThreadManager;
import com.sgu6.middleware.util.FileUtil;

import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

public class Logger {

    private static final int VERBOSE = 0;
    private static final int DEBUG = 1;
    private static final int INFO = 2;
    private static final int WARNING = 3;
    private static final int ERROR = 4;


    public static Logger mInstance = null;
    private static int LOG_LEVEL = VERBOSE;
    private static final String LOCAL_PATH = Environment.getExternalStorageDirectory().getPath();
    private static final String LOG_FILE_PATH = LOCAL_PATH + "/sgu6/logs/log.log";
    private static File logFile;

    static {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = (cal.get(Calendar.MONTH))+1;
        int day_of_month = cal.get(Calendar.DAY_OF_MONTH);
        int minute = cal.get(Calendar.MINUTE);
        logFile = FileUtil.makeFilePath("/sgu6/logs/", year+"-"+month+"-"+day_of_month+".log");
    }

    public static Logger getInstance() {
        if (mInstance == null) {
            synchronized (Logger.class) {
                if (mInstance == null) {
                    mInstance = new Logger();
                }
            }
        }
        return mInstance;
    }

    // verbose
    public static void v(String tag, String msg, boolean enabled) {
        if (msg == null)
            return;
        Log.v(tag, msg);
        write("VERBOSE", tag, msg, enabled);
    }

    // debug
    public static void d(String tag, String msg, boolean enabled) {
        if (msg == null)
            return;
        Log.d(tag, msg);
        write("DEBUG", tag, msg, enabled);
    }

    // info
    public static void i(String tag, String msg, boolean enabled) {
        if (msg == null)
            return;
        Log.i(tag, msg);
        write("INFO", tag, msg, enabled);
    }


    // warning
    public static void w(String tag, String msg, boolean enabled) {
        if (msg == null)
            return;
        Log.w(tag, msg);
        write("WARNING", tag, msg, enabled);
    }


    public static void w(String tag, String msg, boolean enabled, Throwable tr) {

    }

    // error
    public static void e(String tag, String msg, boolean enabled) {
        if (msg == null)
            return;
        Log.e(tag, msg);
        write("ERROR", tag, msg, enabled);
    }

    /**
     * 写到文件中的log的前缀，如果因为混淆之类的原因而取不到，就返回"[ minify ]"
     *
     * @return prefix
     */
    private String getPrefixName() {
        StackTraceElement[] sts = Thread.currentThread().getStackTrace();
        if (sts == null || sts.length == 0) {
            return "[ minify ]";
        }
        try {
            for (StackTraceElement st : sts) {
                if (st.isNativeMethod()) {
                    continue;
                }
                if (st.getClassName().equals(Thread.class.getName())) {
                    continue;
                }
                if (st.getClassName().equals(this.getClass().getName())) {
                    continue;
                }
                if (st.getFileName() != null) {
                    return "[ " + Thread.currentThread().getName() +
                            ": " + st.getFileName() + ":" + st.getLineNumber() +
                            " " + st.getMethodName() + " ]";
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "[ minify ]";
    }

    /**
     * 追加文件：使用FileWriter
     *
     * @param level   等级
     * @param prefix  前缀
     * @param content 内容
     * @param enabled 是否开启打印日志
     */
    private static void write(final String level, final String prefix, final String content, boolean enabled) {
        if (!enabled)
            return;
        ThreadManager.getThreadPollProxy().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
                    FileWriter writer = new FileWriter(logFile, true);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                    String time = sdf.format(new Date());
                    writer.write(time + ": " + level + "/" + prefix + ": " + content + "\n");
                    writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

}
